import { NextResponse } from 'next/server';
import { getUser } from '@/lib/authUtils';
const tencentcloud = require("tencentcloud-sdk-nodejs-tts");
import prisma from '@/lib/prisma';
const TtsClient = tencentcloud.tts.v20190823.Client;

const clientConfig = {
  credential: {
    secretId: process.env.TENCENT_SECRET_ID,
    secretKey: process.env.TENCENT_SECRET_KEY,
  },
  region: "",
  profile: {
    httpProfile: {
      endpoint: "tts.tencentcloudapi.com",
    },
  },
};

const client = new TtsClient(clientConfig);

export async function POST(request: Request) {
  try {
    const { text, code, speed } = await request.json();
    
    const params = {
      Text: text,
      SessionId: crypto.randomUUID(),
      VoiceType: code,
      Speed: speed,
    };
    const userid = await getUser(request)
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }
    await prisma.vms_user.update({
        where: { id: userid },
        data: {
          voice_count: {
            increment: 1
          }
        }
      })

    const data = await client.TextToVoice(params);
    
    return NextResponse.json({
      success: true,
      data: data.Audio
    });

  } catch (err: any) {
    console.error("error", err);
    return NextResponse.json({
      success: false,
      message: err.message
    }, { status: 500 });
  }
}